<?php
/**
 * @property int $id
 * @property string $name
 */
class Category extends ActiveRecord
{
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return 'category';
	}

	public function attributeLabels()
	{
		return array(
			'name' => 'Название',
		);
	}

	public function relations()
	{
		return array(
			'article' => array(self::HAS_ONE, 'Article', 'category_id'),
		);
	}

	public function rules()
	{
		return array(
			array('name', 'required'),
			array('name', 'unique', 'on' => 'ajax'),
			array('id, name', 'safe'),
		);
	}
	
	public function search()
	{
		$criteria = new CDbCriteria;
		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name, true);
		return new CActiveDataProvider('Category', array(
			'criteria'=>$criteria,
			'sort'=>array(
				'defaultOrder'=>'id DESC',
			),
		));
	}
	
	/**
	 * @return array  array(id=>name)
	 */
	public function getAllNames()
	{
		$sql = "SELECT id, name FROM category";
		$list = $this->getDbConnection()->createCommand($sql)->queryAll();
		$res = array();
		foreach ($list as $item)
			$res[ $item['id'] ] = $item['name'];
		return $res;
	}
}